import { message } from "antd"
import axios from "axios"
import cookies from "./cookies.js"
import history from "./history"

const URL_BASE = "http://182.106.191.230:9999/micapi"
// const URL_BASE = "http://localhost:3000/admin/api"
const service = axios.create({
  baseURL: URL_BASE,
  timeout: 20000,
})
// 请求拦截
service.interceptors.request.use(
  (config) => {
    const token = cookies.get("react-token")
    if (token && token !== "undefined" && config.isToken) {
      config.headers["Authorization"] = "Bearer " + token
    }
    // if (config.data && !config.headers["Content-Type"]) {
    //   config.headers["Content-Type"] = "application/x-www-form-urlencoded"
    //   config.data = qs.stringify(config.data)
    // }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  (response) => {
    // // 下载文件
    // const headers = response.headers
    // if (
    //   headers["content-disposition"] &&
    //   headers["content-type"] === "application/vnd.ms-excel;charset=utf-8"
    // ) {
    //   return response
    // }
    const res = response.data

    if (res.code !== 200 && res.status !== "1") {
      message.error(res.message || "接口错误", 2)
      if (res.code === 401) {
        cookies.remove("react-token")
        cookies.remove("refreshToken")
        cookies.remove("refreshTime")
        cookies.remove("loginTime")
        history.push("/login")
        window.location.reload()
      }
      return Promise.reject(new Error(res.message || "Error"))
    } else {
      return res
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
